<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/7/10 14:55
 */

namespace App\Models\Observer;

use App\Models\MarriageHistory;
use App\Models\MedicalRecord;
use Illuminate\Database\Eloquent\Model;

class PatientObserver extends UserObserver
{
    public function saved(Model $patient)
    {
        //  清除缓存
        $this->removeCache($patient);

        if ($patient->isDirty('sex')) {
            //  事件触发时 属性字段没有同步到原始数据中
            if ($patient->male()) {
                $records = MedicalRecord::select('id')->wherePatientId($patient->getKey())->get();

                $result = MarriageHistory::whereIn('record_id', $records->toArray())->update([
                    'macrosomia'   => null,
                    'menstruation' => '',
                    'menopause'    => '',
                ]);
            }
        }
    }

    public function created(Model $patient)
    {
        parent::created($patient);

        $this->createHx($patient);
    }

    public function relation(Model $model)
    {
        \DB::table('tn_patient')->insert(['account' => $model->account]);
    }

    public function deleted(Model $patient)
    {
        $this->removeCache($patient);
    }
}